const express = require('express')
const router = express.Router()
const User = require('../../models/Users')
const bcrypt = require('bcrypt')
const gravatar = require('gravatar');
const jwt = require('jsonwebtoken');
// const JwtStrategy = require('passport-jwt').Strategy,
const passport = require('passport')
const  keys =  require('../../config/keys')
router.get("/test",(req,res) => {
    res.json({msg:"is ok"})
})
router.post("/register/:doctorID", (req,res) =>{
    User.findOne({username:req.body.username})
        .then(user => {
            if(user){
                return res.status(201).json("用户名已存在!")
            }else{
                const avatar = gravatar.url('req.body.email', {s: '200', r: 'pg', d: 'mm'});
                const newUser = new User({
                    username:req.body.username,
                    password:req.body.password,
                    jobNumber:req.body.jobNumber,
                    doctorID:req.params.doctorID
                })
                bcrypt.genSalt(10, function(err, salt) {
                    bcrypt.hash(newUser.password, salt, (err, hash) => {
                        if(err) throw err;
                        newUser.password = hash;
                        newUser.save()
                               .then(user => res.status(200).json(user))
                               .catch(err => console.log(err))
                        // Store hash in your password DB.
                    });
                });
            }

        })
})
router.post('/login',(req,res) => {
    const username = req.body.username
    const password = req.body.password
    User.findOne({username})
        .then(user => {
            if(!user){
                return res.status(201).json('用户不存在')
            }
            bcrypt.compare(password, user.password)
                  .then(isMath => {
                      if(isMath){
                          const rule = {id:user.id,name:user.name,jobNumber:user.jobNumber}
                          jwt.sign(rule,keys.secretOrKey,{expiresIn:3600},(err,token) => {
                              if(err) return err
                              res.json({
                                  success:true,
                                  token:'Bearer ' + token,
                                  user:user
                              })
                          })
                      }else{
                          return res.status(201).json('密码错误')
                      }
                  })
        })
})
router.get('/current',passport.authenticate('jwt',{session:false}),(req,res) => {
    res.json({
        id:req.user.id,
        name:req.user.name,
        email:req.user.email
    })
})

module.exports = router